﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using IESN.DAL;
using IESN.Enum;
using IESN.Common;
using IESN.Tools;

namespace IESN
{
    public partial class UserManagementFrm : XtraForm
    {
        List<ComboboxCommonObj> UserType = new List<ComboboxCommonObj>();
        List<ComboboxCommonObj> StatusList = new List<ComboboxCommonObj>();
        public UserManagementFrm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent;

            UserType.Add(new ComboboxCommonObj() { ID = "1", Name = "管理员" });
            UserType.Add(new ComboboxCommonObj() { ID = "2", Name = "操作员" });
            cbbLevel.DataSource = UserType;
            cbbLevel.ValueMember = "ID";
            cbbLevel.DisplayMember = "Name";

            StatusList.Add(new ComboboxCommonObj() { Status = true, Name = "启用" });
            StatusList.Add(new ComboboxCommonObj() { Status = false, Name = "禁用" });
            cbbStatus.DataSource = StatusList;
            cbbStatus.ValueMember = "Status";
            cbbStatus.DisplayMember = "Name";
        }

        private void FrmUserManagement_Load(object sender, EventArgs e)
        {
            try
            {
                // TODO: 这行代码将数据加载到表“iESNDataSet.UserAccount”中。您可以根据需要移动或删除它。
                this.userAccountTableAdapter.Fill(this.iESNDataSet.UserAccount);
                this.gridView1.RowClick += new DevExpress.XtraGrid.Views.Grid.RowClickEventHandler(gridView1_RowClick);
                InitUI();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.Error(ex.Message, ex);
            }
        }

        private DataRow currentSelectedDataRow = null;
        void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            CancelToAdd();
            System.Data.DataRowView aDataRowView = this.gridView1.GetRow(e.RowHandle) as System.Data.DataRowView;
            currentSelectedDataRow = aDataRowView.Row;
        }

        private void InitUI(bool aInputEnable = false, OperationType optType = OperationType.None)
        {
            this.txtUserName.Enabled = aInputEnable;
            this.txtPWD.Enabled = aInputEnable;
            this.txtRemark.Enabled = aInputEnable;
            this.cbbLevel.Enabled = aInputEnable;
            this.cbbStatus.Enabled = aInputEnable; 
            this.btnSave.Enabled = aInputEnable;
            this.btnCancel.Enabled = aInputEnable;

            switch (optType)
            {
                case  OperationType.Add:
                    this.btnAdd.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDel.Enabled = false;
                    this.btnReflesh.Enabled = false;
                    break;
                case OperationType.Update: 
                    this.btnAdd.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDel.Enabled = false;
                    this.btnReflesh.Enabled = false;
                    break;
                case OperationType.Cancel:
                case OperationType.Save:
                    this.btnAdd.Enabled = true;
                    this.btnModify.Enabled = true;
                    this.btnDel.Enabled = true;
                    this.btnReflesh.Enabled = true;
                    break;
                default:
                    break;
            }
        }

        private string GetNewId(DataTable dt)
        {
            var aMaxID = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                var aRowId = dr["UserID"].ToString();
                if (string.IsNullOrWhiteSpace(aMaxID))
                {
                    aMaxID = aRowId;
                }

                if (int.Parse(aMaxID) < int.Parse(aRowId))
                {
                    aMaxID = aRowId;
                }
            }

            return (int.Parse(aMaxID) + 1).ToString();
        }

        private OperationType currentOperationType = OperationType.None;
        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.gridView1.AddNewRow();
            InitUI(true, OperationType.Add);
            currentSelectedDataRow = this.gridView1.GetFocusedDataRow();
            var aNewId = GetNewId(currentSelectedDataRow.Table);
            //设置新用户的默认值
            currentSelectedDataRow.SetField("UserID", aNewId);
            currentSelectedDataRow.SetField("UserLevel", "2");
            currentSelectedDataRow.SetField("Status", true);
            cbbStatus.ResetText();
            currentOperationType = OperationType.Add;
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            InitUI(true, OperationType.Update);
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (currentSelectedDataRow == null)
            {
                return;
            }

            try
            {
                if (MessageBox.Show("确实要删除该用户吗？", "删除用户",  MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    this.gridView1.DeleteSelectedRows();
                    this.iESNDataSet.AcceptChanges();
                    this.userAccountTableAdapter.Update(iESNDataSet);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.Error(ex.Message, ex);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (currentSelectedDataRow == null)
            {
                return;
            }

            var aNullUserName = currentSelectedDataRow["UserName"] == null || string.IsNullOrWhiteSpace(currentSelectedDataRow["UserName"].ToString());
            if (aNullUserName)
            {
                MessageBox.Show("用户名不能为空!");
                return;
            }

            var aNullPwd = currentSelectedDataRow["UserPwd"] == null || string.IsNullOrWhiteSpace(currentSelectedDataRow["UserPwd"].ToString());
            if (aNullPwd)
            {
                MessageBox.Show("密码不能为空!");
                return;
            } 

            try
            {
                currentSelectedDataRow.EndEdit();
                if (currentSelectedDataRow.RowState == DataRowState.Detached)
                {
                    this.gridView1.UpdateCurrentRow();
                }

                this.userAccountTableAdapter.Update(currentSelectedDataRow);
                this.userAccountBindingSource.ResetBindings(false);
                InitUI(false, OperationType.Save);
            }
            catch(Exception ex)
            {
                LogHelper.Instance.Error(ex.Message, ex);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            CancelToAdd();
        }

        private void CancelToAdd()
        {
            InitUI(false, OperationType.Cancel);
            if (currentOperationType == OperationType.Add && currentSelectedDataRow != null && currentSelectedDataRow.RowState == DataRowState.Added)
            {
                currentSelectedDataRow.Delete();
                currentSelectedDataRow = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            }
        }

        private void btnReflesh_Click(object sender, EventArgs e)
        {
            this.userAccountTableAdapter.GetData();
        }
         
        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            GridView aGv = sender as GridView;

            if (e.Column.FieldName == "UserLevel")
            {
                switch (e.DisplayText)
                {
                    case "1":
                        e.DisplayText = "管理员";
                        break;
                    case "2":
                        e.DisplayText = "操作员";
                        break;
                    default:
                        break;
                }
            }
        }

    }
     
}
